﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Configuration;

namespace QASampling.Util
{
    public class CryptoHelper
    {
        //private readonly string IV = "SuFjcEmp/TE=";
        private static readonly string IV = "SuFjcEmp/TE=";
        //private readonly string Key = "KIPSToILGp6fl+3gXJvMsN4IajizYBBT";
        private static readonly string Key = "KIPSToILGp6fl+3gXJvMsN4IajizYBBT";

        public static string Encrypt(string plainText)
        {
            TripleDESCryptoServiceProvider provider = GetCryptoProvider();

            using (MemoryStream mStream = new MemoryStream())
            {
                using (CryptoStream cStream = new CryptoStream(mStream, provider.CreateEncryptor(), CryptoStreamMode.Write))
                {

                    byte[] toEncrypt = new UTF8Encoding().GetBytes(plainText);

                    cStream.Write(toEncrypt, 0, toEncrypt.Length);
                    cStream.FlushFinalBlock();

                    byte[] ret = mStream.ToArray();

                    return Convert.ToBase64String(ret);
                }
            }
        }

        private static TripleDESCryptoServiceProvider GetCryptoProvider()
        {
            TripleDESCryptoServiceProvider provider = new TripleDESCryptoServiceProvider();
            provider.IV = Convert.FromBase64String(IV);
            provider.Key = Convert.FromBase64String(Key);
            return provider;
        }

        public static string Decrypt(string chiperText)
        {
            TripleDESCryptoServiceProvider provider = GetCryptoProvider();
            byte[] inputEquivalent = Convert.FromBase64String(chiperText);

            using (MemoryStream msDecrypt = new MemoryStream())
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, provider.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    csDecrypt.Write(inputEquivalent, 0, inputEquivalent.Length);
                    csDecrypt.FlushFinalBlock();
                    return new UTF8Encoding().GetString(msDecrypt.ToArray());
                }
            }
        }
    }
}
